/**
 * Created by Kpeng on 2017/7/12.
 * Depending on the jquery-1.11.3.min.js.
 * Depending on the style.css.
 * To cite this document, always state the source as shown above.
 */
var recoveryOrder = new Array(0);

if (!erpWrap) {
  var erpWrap = {}
}

erpWrap.init = function () {
  $("#content-container").css("width", $(document).width() - 200);

  erpWrap.topClick(); //顶部菜单点击
  erpWrap.popTitle(); //顶部菜单触发自定义Title
  erpWrap.tabNav();    //tab导航
  erpWrap.addTool();  //附加功能
  erpWrap.tabRecovery();  //tab恢复
};

//弹出提示，替换标签默认title属性
erpWrap.popTitle = function () {
  var pageWrap = $('#pageWrap');
  pageWrap.find('.pop-tip').popup({
    inline: true,
    hoverable: true,
    position: 'top left',
    delay: {
      show: 300,
      hide: 800
    }
  });
};

//顶部菜单点击
erpWrap.topClick = function () {
  $(".top-link").on("click", function (e) {
    e.preventDefault();
    erpWrap.menuHandler(e);
    return false;
  });
}

//Tab主导航切换
erpWrap.tabNav = function () {
  var tabNavWrap = $("#tab-nav-wrap");

  //tab切换
  tabNavWrap.on('click', ".tab", function (e) {
    sessionStorage.setItem("active_tab", $(this).data("mid").toString());
  });

  //tab关闭
  tabNavWrap.on('click', '.close-current', function (e) {
    e.stopPropagation();

    var current = $(this).parent(),
        items = tabNavWrap.find('.tab'),
        itemLen = tabNavWrap.find('.tab').length, //所有导航菜单除去主页
        getIndex = current.index() - 1,
        recoveryOrder = window.recoveryOrder;

    itemLen -= 1;
    current.remove(); //关闭当前

    for (var i = 0, len = recoveryOrder.length; i < len; i++) {
      if (recoveryOrder[i] === current.data("mid")) {
        recoveryOrder.splice(i, 1);
        break;
      }
    }
    var recoveryOrderStr = JSON.stringify(recoveryOrder);
    sessionStorage.setItem("recoveryOrder", recoveryOrderStr);
    sessionStorage.removeItem("index_" + current.data("mid"));
    sessionStorage.removeItem("content_" + current.data("mid"));

    if (itemLen === 1 || current.hasClass('active')) {
      sessionStorage.setItem("active_tab",
      items.eq(getIndex).data("mid").toString());
      items.eq(getIndex).addClass('active');
      items.eq(getIndex).trigger("click");
    }
    return;
  });
};

//刷新TAB恢复
erpWrap.tabRecovery = function () {
  var isSet = sessionStorage.getItem("recoveryOrder") === null ? false : true,
      recoveryOrder = window.recoveryOrder;

  if (isSet) {
    var tabNav = $('#tab-nav-wrap').find('.tabs'),
        recoveryOrder = JSON.parse(sessionStorage.getItem("recoveryOrder"));

    window.recoveryOrder = recoveryOrder;

    for (var i = 0, len = recoveryOrder.length; i < len; i++) {
      var keyNumber = recoveryOrder[i];

      if (keyNumber !== 100) {
        var url = sessionStorage.getItem("index_" + keyNumber),
            content = sessionStorage.getItem("content_" + keyNumber),
            tabItem = '<a href="#" class="item tab" data-mid="' + keyNumber
                      + '" data-href="' + url + '">' + content
                      + '<span class="close-current"></span></a>';

        $(tabItem).on("click", erpWrap.tabChangeHandler).appendTo(tabNav);
      } else {
        $("#tab-nav-wrap a[data-mid=\"100\"]").on("click", erpWrap.tabChangeHandler);
      }
    }

    //恢复激活状态
    var activeId = sessionStorage.getItem("active_tab");
    $("#tab-nav-wrap a[data-mid=\"" + activeId + "\"]").addClass("active").trigger("click");
  } else {
    var homeItem = $("#tab-nav-wrap .home");

    recoveryOrder.push(homeItem.data("mid"));
    var recoveryOrderStr = JSON.stringify(recoveryOrder);
    sessionStorage.setItem("recoveryOrder", recoveryOrderStr);

    sessionStorage.setItem("active_tab", "100");
    sessionStorage.setItem("index_" + homeItem.data("mid"), homeItem.data("href"));
    sessionStorage.setItem("content_" + homeItem.data("mid"), homeItem.text().trim());
    homeItem.addClass("active").click(erpWrap.tabChangeHandler);
    homeItem.trigger("click");
  }
}

//菜单点击回调
erpWrap.menuHandler = function (e) {
  var cItem = e.currentTarget;

  if ($(cItem).attr("href") === "") {
    return true;
  } else {
    var getCurItemText = $(cItem).data("content") || $(cItem).text() ||
            ($(cItem).find("span").length > 0 ? $(cItem).find("span").eq(1).text() : "");

    //添加菜单激活状态
    erpWrap.menuActiveHandler(cItem);
    erpWrap.insertTab($(cItem).data("mid"), getCurItemText, $(cItem).attr('href'));

    // //附加到主导航
    // menuChecked.removeClass('active');
    // menuChecked.each(function () {
    //   if (this.innerText === getCurItemText) {  //如果已存在
    //     isFlag = true;
    //     $(this).trigger('click');
    //     return false;
    //   } else {
    //     isFlag = false;
    //     return true;
    //   }
    // });

    // if (!isFlag) {
    //   var tabItem = '<a href="#" class="item tab active" data-mid="' + $(cItem).data("mid").toString() + '" data-href=' + $(cItem).attr('href') + '> ' + getCurItemText
    //               + '<span class="close-current"></span></a>';

    //   if (menuChecked.length < maxLength) {
    //     var newItem = $(tabItem).on("click", erpWrap.tabChangeHandler).appendTo(
    //         tabNav);

    //     recoveryOrder.push($(tabItem).data("mid"));
    //     var recoveryOrderStr = JSON.stringify(recoveryOrder);
    //     sessionStorage.setItem("recoveryOrder", recoveryOrderStr);

    //     sessionStorage.setItem("active_tab", $(tabItem).data("mid").toString());
    //     sessionStorage.setItem("index_" + $(tabItem).data("mid"),
    //         $(tabItem).data("href"));
    //     sessionStorage.setItem("content_" + $(tabItem).data("mid"),
    //         getCurItemText.trim());
    //     erpWrap.replaceFrame(newItem);
    //   } else {
    //     menuChecked.last().trigger('click');
    //     layer.msg("最多只能同时打开" + maxLength + "个页面")
    //   }
    // }
  }
}

erpWrap.replaceFrame = function (_selector) { //替换iframe的src
  var iframe = document.querySelector('#iframe'),
      getHref = $(_selector).data('href');
  if (getHref) {
    iframe.src = getHref;
  }
}

erpWrap.menuStatusHandler = function (item) {
  //展开菜单
  var _this = item,
      cItem = $("#menu").find("a[href='" + $(_this).attr("data-href") + "']"),
      pItem = cItem.parents(".eknows-menu-sub");

  if ($("#menu").eknowsmenu("isOpen")) {
    if (pItem.length > 0) {
      if (!pItem.hasClass("eknows-menu-open")) {
        pItem.children("a").trigger("click");
      }
    } else {
      $("#menu").find(".eknows-menu-open").children("a").trigger("click");
    }

    erpWrap.menuActiveHandler(cItem);
  }
}

erpWrap.menuActiveHandler = function (item) {
  $("#menu a").removeClass("eknows-menu-active-item");

  if (!$(item).hasClass("top-link")) {
    $(item).addClass("eknows-menu-active-item");
  }
}

erpWrap.tabChangeHandler = function (e) {
  var _this = e.currentTarget;

  $(_this).addClass("active").siblings().removeClass("active");

  erpWrap.replaceFrame($(_this));
  erpWrap.menuStatusHandler(_this);
}

//关闭其它页和刷新页面
erpWrap.addTool = function () {
  var addTool = $('#addTools'),
      tabs = $('#tab-nav-wrap').find('.tabs');

  //关闭其它
  addTool.on('click', '.closeOther', function () {
    tabs.find('.item').not('.home ,.active').remove();
  });
  //刷新页面
  addTool.on('click', '.refreshIfm', function () {
    tabs.find('.active').click();
  });
}

erpWrap.insertTab = function (mid, title, url) {
  var tabNav = $('#tab-nav-wrap').find('.tabs'),
      maxLength = 10,
      isFlag = true,
      menuChecked = tabNav.find('.item'),
      recoveryOrder = window.recoveryOrder;
      
  //附加到主导航
  menuChecked.removeClass('active');
  menuChecked.each(function () {
    if (this.innerText === title) {  //如果已存在
      isFlag = true;
      $(this).trigger('click');
      return false;
    } else {
      isFlag = false;
      return true;
    }
  });

  if (!isFlag) {
    var tabItem = '<a href="#" class="item tab active" data-mid="' + mid + '" data-href=' + url + '> ' + title
                + '<span class="close-current"></span></a>';

    if (menuChecked.length < maxLength) {
      var newItem = $(tabItem).on("click", erpWrap.tabChangeHandler).appendTo(tabNav);

      recoveryOrder.push(mid);
      var recoveryOrderStr = JSON.stringify(recoveryOrder);
      sessionStorage.setItem("recoveryOrder", recoveryOrderStr);

      sessionStorage.setItem("active_tab", mid + "");
      sessionStorage.setItem("index_" + mid, url);
      sessionStorage.setItem("content_" + mid, title);
      erpWrap.replaceFrame(newItem);
    } else {
      menuChecked.last().trigger('click');
      layer.msg("最多只能同时打开" + maxLength + "个页面")
    }
  }
}